package com.example.wuqujingdianphone.activity;

import android.Manifest;
import android.app.Service;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dou361.ijkplayer.widget.PlayStateParams;
import com.dou361.ijkplayer.widget.PlayerView;
import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.base.BaseActivity;
import com.example.wuqujingdianphone.utils.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AudioPlayToActivity extends BaseActivity implements View.OnClickListener {
    private String url = "";
    private String title = "";
    private String bac = "";
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.title)
    TextView mTitle;

    private ImageView play, stop, ivv;
    private TextView musicLength, musicCur;
    private SeekBar seekBar;
    private RelativeLayout bac_audio;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private AudioManager audioManager;

    private Timer timer;

    int maxVolume, currentVolume;

    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private int currentPosition;//当前音乐播放的进度

    SimpleDateFormat format;

    private boolean isPause = false;//是否暂停
    private boolean isFirst = false;//diyici

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_play);
        ButterKnife.bind(this);
        title = getIntent().getStringExtra("title");
        bac = getIntent().getStringExtra("bac");
        url = getIntent().getStringExtra("playUrl");
        mTitle.setText(title);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initView();
    }

    private void initView() {
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);

        format = new SimpleDateFormat("mm:ss");

        play = findViewById(R.id.play);
        stop = findViewById(R.id.stop);

        musicLength = (TextView) findViewById(R.id.music_length);
        bac_audio = findViewById(R.id.bac_audio);
        musicCur = (TextView) findViewById(R.id.music_cur);
        ivv = findViewById(R.id.ivvv);

        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());

        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        Glide.with(this)
                .load(bac)
                .error(R.drawable.icon_book_cover_defalt)
                .placeholder(R.drawable.icon_book_cover_defalt)
                .centerCrop()
                .into(ivv);


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            initMediaPlayer();//初始化mediaplayer
        }
    }

    private void initMediaPlayer() {
        try {
//            mediaPlayer.setDataSource("/sdcard/music.mp3");//指定音频文件的路径
            mediaPlayer.setDataSource(url);//指定音频文件的路径
            mediaPlayer.prepare();//让mediaplayer进入准备状态
            mediaPlayer.setLooping(true);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(mediaPlayer.getDuration());
                    musicLength.setText(format.format(mediaPlayer.getDuration()) + "");
                    musicCur.setText("00:00");
                    //musicName.setText("music.mp3");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 &&
                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                } else {
                    ToastUtil.show("拒绝使用");
                    finish();
                }
                break;
            default:
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play:
                if (!isFirst) {
                    isFirst = true;
                    if (!mediaPlayer.isPlaying()) {
                        play.setImageResource(R.mipmap.ic_play_btn_pause_pressed);
                        mediaPlayer.start();//开始播放
                        mediaPlayer.seekTo(currentPosition);

                        //监听播放时回调函数
                        timer = new Timer();
                        timer.schedule(new TimerTask() {

                            Runnable updateUI = new Runnable() {
                                @Override
                                public void run() {
                                    musicCur.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                                }
                            };

                            @Override
                            public void run() {
                                if (!isSeekBarChanging) {
                                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                    runOnUiThread(updateUI);
                                }
                            }
                        }, 0, 50);
                    } else {
                        mediaPlayer.pause();//暂停播放
                    }
                } else {
                    if (!isPause) {
                        isPause = true;
                        mediaPlayer.pause();//暂停播放
                        play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
                    } else {
                        isPause = false;
                        mediaPlayer.start();//播放
                        play.setImageResource(R.mipmap.ic_play_btn_pause_pressed);
                    }
                }


                // if (mediaPlayer.isPlaying()) {
                //mediaPlayer.pause();//暂停播放

                break;
            case R.id.stop:

                if (mediaPlayer.isPlaying() || isPause) {
                    isFirst = false;
                    isPause = false;
                    play.setImageResource(R.mipmap.ic_play_btn_play_pressed);
                    mediaPlayer.reset();//停止播放
                    initMediaPlayer();
                }
                break;
//            //音量加
//            case R.id.volume_plus:
//                maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);
//                currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//                Toast.makeText(this,"音量增加,最大音量是：" + maxVolume + "，当前音量" + currentVolume,
//                        Toast.LENGTH_SHORT).show();
//                break;
//            //音量减
//            case R.id.volume_decrease:
//                maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);
//                currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//                Toast.makeText(this,"音量减小,最大音量是：" + maxVolume + "，当前音量" + currentVolume,
//                        Toast.LENGTH_SHORT).show();
//                break;
//            default:
//                break;
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        isSeekBarChanging = true;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }
}
